package com.yc.c112s3plyblog.controller;

import com.ly.upload.vo.Result;
import com.ly.upload.web.UploadController;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

@RestController
public class UEditorAction {

    // 定义控制器替代  controller.jsp
    @RequestMapping(path = "/ueditor/jsp/controller.jsp",
            params = "action=config")
    public ConfigInfo controller(String action) {
        return new ConfigInfo(
                "upload",
                "image",
                "/");
    }

    @Resource
    UploadController uploadController;

    @RequestMapping(value = "/ueditor/jsp/controller.jsp",
            params = "action=upload")
    public UploadResult controller1(String action, @RequestParam("image") MultipartFile file) {
        try {
            final Result result = uploadController.upload(file);
            return new UploadResult("SUCCESS",
                    // 要去掉第一个 /
                    result.getData().toString().substring(1),
                    file.getOriginalFilename(),
                    file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            return new UploadResult("FAILURE", null,
                    file.getOriginalFilename(),
                    file.getOriginalFilename());
        }
    }


}

// UEditor 文件上传配置信息
@Data
@AllArgsConstructor
@NoArgsConstructor
class ConfigInfo {
    //执行上传图片的action名称,
    private String imageActionName;
    //提交的图片表单名称
    private String imageFieldName;
    //图片访问路径前缀
    private String imageUrlPrefix;
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class UploadResult{
    private String state;
    private String url;
    private String title;
    private String original;
}
